<template>
  <div class="login">
    <van-form @submit="onSubmit">
      <van-field
        v-model="phone"
        name="phone"
        clearable
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="code"
        name="code"
        center
        clearable
        label="验证码"
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            native-type="button"
            @click="handleGetCode"
            :disabled="disabled"
          >{{ disabled ? btnText : '发送验证码' }}</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { getCodeByPhone } from '../../api/user'
export default {
  name: 'Login',
  data() {
    return {
      phone: '13199887766',
      code: '',
      start: JSON.parse(sessionStorage.getItem('code_timestamp')) || 0, // 发送验证码按下的起始时间
      btnText: '', // 发送验证码按钮上的文本
    }
  },
  computed: {
    disabled() {
      if (this.start === 0) {
        return false
      }
      return Date.now() - this.start < 10000
    },
  },
  methods: {
    onSubmit(values) {
      // 在组件中调用到 store 中的 action 方法
      // 不能直接调用，要 store.dispatch(action)
      const result = this.$store.dispatch('user/loginAction', values)
      console.log('result:', result)
      result.then(data => {
        console.log('then:', data)
        if (data) {
          this.$router.push('/mine')
        } else {
          Toast.fail({
            message: '手机号或验证码有误',
          })
        }
      })
    },
    timer() {
      this.btnText = `重新发送(${10 - Math.floor((Date.now() - this.start) / 1000)})`

      console.log('btnText:', this.btnText)
      if (Date.now() - this.start >= 10000) {
        this.start = 0
        return
      }

      this.timerId = setTimeout(this.timer, 1000)
    },
    /**
     * 发送验证码处理
     */
    handleGetCode() {
      if (this.phone.length === 0) {
        return
      }
      // 记录按钮按下的起始时间
      this.start = Date.now()
      // 启动倒计时功能
      this.timer()
      // 将按下时间的时间保存到 sessionStorage 中
      sessionStorage.setItem('code_timestamp', JSON.stringify(this.start))

      // 获取验证码
      getCodeByPhone(this.phone)
        .then(data => {
          console.log('验证码:', data)
          Toast.success({
            message: '验证码：' + data.code,
          })
          this.code = data.code
        })
        .catch(error => console.error('异常:', error))
    },
  },
  created() {
    this.timer()
  },
  beforeDestroy() {
    // 清除定时器
    clearTimeout(this.timerId)
  },
}
</script>

<style lang="less" scoped>

</style>
